package com.example.rf.api

import com.example.rf.dao.PostDao
import com.example.rf.entity.Post
import com.example.rf.service.PostService
import kotlinx.coroutines.reactive.awaitFirst
import kotlinx.coroutines.reactive.awaitFirstOrNull
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/post")
open class PostApi(val postDao: PostDao, val postService: PostService) {


    @GetMapping("all")
    open suspend fun all(): List<Post> {
        return postDao.findAll().collectList().awaitFirst();
    }

    @GetMapping("create")
    open suspend fun create(post: Post): Post {
        return postDao.save(post).awaitFirst()
    }

    @GetMapping("/{id}")
    open suspend fun get(@PathVariable("id") id: Int): Post? {
        return postDao.findById(id).awaitFirstOrNull()
    }

    @GetMapping("/findByTitleContains")
    open suspend fun findByTitleContains(name: String): List<Post> {
        return postDao.findByTitleContains(name)
    }

    @GetMapping("/test")
    open suspend fun test(): List<Post> {
        return postService.test1()
    }

    @GetMapping("/{id}/update")
    open suspend fun update(@PathVariable("id") id: Int, post: Post): Post {
        return postDao.findById(id)
            .map { p ->
                p!!.title = post.title
                p.content = post.content
                p
            }
            .flatMap { p -> postDao.save(p) }
            .awaitFirst();
    }

    @GetMapping("/{id}/delete")
    open suspend fun delete(@PathVariable("id") id: Int) {
        postDao.deleteById(id).awaitFirst()
    }
}